package com.ssh.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import com.ssh.model.Goods;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.ssh.service.IGoodsService;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;

public class GoodsAction extends ActionSupport {
	
	private Goods g = new Goods();
	private List<Goods> goodsList = new ArrayList<Goods>();
	private static IGoodsService goodsService = null;
	private String name;

	public IGoodsService getGoodsService() {
		if (goodsService == null) {
			ServletContext sc = ServletActionContext.getServletContext();
			ApplicationContext ac = WebApplicationContextUtils
					.getRequiredWebApplicationContext(sc);
			goodsService = (IGoodsService) ac.getBean("GoodsService");
			if (goodsService == null)
				System.out.println("error");
		}
		return goodsService;
	}
	
	/**
	 * 获得所有物品信息
	 */
	public void getAllGoods() {

		goodsList = getGoodsService().findAll();
		
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/json");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}

		String json = new Gson().toJson(goodsList);
//		System.out.println(json);
		out.println(json);

		out.flush();
		out.close();
	}

	public void setGoodsService(IGoodsService goodsService) {
		this.goodsService = goodsService;
	}

	public Goods getG() {
		return g;
	}

	public void setG(Goods g) {
		this.g = g;
	}

	public List<Goods> getGoodsList() {
		return goodsList;
	}

	public void setGoodsList(List<Goods> goodsList) {
		this.goodsList = goodsList;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return this.name;
	}
}